const express = require('express');
const router = express.Router();
const upload = require('../utils/fileUpload');
const fs = require('fs');
const path = require('path');

// GET /api/images/get - 获取所有图片
router.get('/get', async (req, res) => {
  try {
    const uploadsDir = path.join(__dirname, '../uploads');
    const files = fs.readdirSync(uploadsDir);

    const images = files.filter(file => {
      const ext = path.extname(file).toLowerCase();
      return ['.jpg', '.jpeg', '.png', '.gif'].includes(ext);
    }).map(file => ({
      name: file,
      url: `http://${req.get('host')}/uploads/${file}`,
      description: ''
    }));

    res.status(200).json({
      code: 200,
      message: '获取图片成功',
      data: images
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '获取图片失败',
      error: error.message
    });
  }
});

// POST /api/images/add - 添加多张图片
router.post('/add', upload.array('images', 10), async (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({
        code: 400,
        message: '请上传至少一张图片'
      });
    }

    const uploadedImages = req.files.map(file => ({
      name: file.originalname,
      url: `http://${req.get('host')}/uploads/${file.filename}`,
      description: ''
    }));

    res.status(201).json({
      code: 201,
      message: '图片添加成功',
      data: uploadedImages
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: '添加图片失败',
      error: error.message
    });
  }
});

// POST /api/images/del - 删除图片
router.post('/del', async (req, res) => {
  try {
    const { filename } = req.body;
    if (!filename) {
      return res.status(400).json({
        code: 400,
        message: '请提供有效的文件名'
      });
    }

    // 构建文件路径
    const filePath = path.join(__dirname, '../uploads', filename);
    
    // 检查文件是否存在
    if (!fs.existsSync(filePath)) {
      return res.status(404).json({
        code: 404,
        message: '图片不存在'
      });
    }

    // 删除文件
    fs.unlinkSync(filePath);
    
    // 返回成功响应
    res.status(200).json({
      code: 200,
      message: '图片删除成功',
      data: { filename }
    });
  } catch (error) {
    console.error('删除图片时出错:', error);
    res.status(500).json({
      code: 500,
      message: '删除图片失败',
      error: error.message
    });
  }
});

module.exports = router; 